package jp.co.itfrontier.mashup.utils {
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import mx.core.Application;
	
	

	public class CrossDomainUtil {

		// サーバーURL
		public static var PROXY_URL:String;

		private var proxyLoader:URLLoader;

		public function CrossDomainUtil(url:String = null) {
			if (url != null) {
				PROXY_URL = url;
			} else {
				PROXY_URL = "http://pc102137a:8080/URLProxy/proxy";
				//PROXY_URL = "http://itfmashup.heteml.jp/proxy.php5";
			}
		}


		/**
		 * Proxyリクエスト
		 */
		public function requestProxy(req:URLRequest, func:Function):void {

			proxyLoader = new URLLoader();
			
			proxyLoader.addEventListener(Event.COMPLETE, func, false, 0.0, false);

			var request:URLRequest = new URLRequest(PROXY_URL);

			var param:URLVariables = new URLVariables();
			param.url = req.url + "?" + encodeURI(parseURLRequest(req));

			request.data = param;
			
			proxyLoader.load(request);				
							
		}
		
		private function callFunction(func:Function):Function {
			return function (event:Event):void {
				var loader:URLLoader = event.target as URLLoader;
				loader.removeEventListener(Event.COMPLETE, callFunction(func));
				
				func(event);
			}
		}
		
		/**
		 * 架空のレスポンスを生成
		 *
		 */
		private function parseURLRequest(req:URLRequest):String {

			var rtn:String = "";
			
			var v:URLVariables = req.data as URLVariables;
			
			for (var s:String in v) {
				rtn += s + "=" + v[s] + "&";
			}

			return rtn.substr(0, rtn.length - 1);				

		}

	}

}